//! HTTP服务器

use std::sync::Arc;
use axum::{
    routing::{get, post},
    Router,
    extract::State,
    response::Json,
    http::StatusCode,
};
use tower::ServiceBuilder;
use tower_http::cors::CorsLayer;
use data_gateway_kernel::DataGatewayKernel;
use crate::handlers::{health_handler, query_handler, status_handler};
use crate::middleware::RequestLoggingLayer;
use serde_json::json;

/// HTTP服务器配置
#[derive(Debug, Clone)]
pub struct HttpServerConfig {
    /// 监听地址
    pub host: String,
    /// 监听端口
    pub port: u16,
    /// 启用CORS
    pub enable_cors: bool,
    /// 请求超时时间（秒）
    pub request_timeout_seconds: u64,
}

impl Default for HttpServerConfig {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: 8080,
            enable_cors: true,
            request_timeout_seconds: 30,
        }
    }
}

/// HTTP服务器
pub struct HttpServer {
    /// 配置
    pub config: HttpServerConfig,
    /// 内核引用
    kernel: Arc<DataGatewayKernel>,
}

impl HttpServer {
    /// 创建新的HTTP服务器
    pub fn new(config: HttpServerConfig, kernel: Arc<DataGatewayKernel>) -> Self {
        Self { config, kernel }
    }

    /// 创建带默认配置的HTTP服务器
    pub fn with_default_config(kernel: Arc<DataGatewayKernel>) -> Self {
        Self::new(HttpServerConfig::default(), kernel)
    }

    /// 创建路由
    pub fn create_router(&self) -> Router {
        let mut router = Router::new()
            .route("/health", get(health_handler))
            .route("/status", get(status_handler))
            .route("/query", post(query_handler))
            .route("/", get(root_handler))
            .with_state(self.kernel.clone());

        // 添加中间件
        let middleware_stack = ServiceBuilder::new()
            .layer(RequestLoggingLayer::new());

        if self.config.enable_cors {
            router = router.layer(CorsLayer::permissive());
        }

        router.layer(middleware_stack)
    }

    /// 启动服务器
    pub async fn start(&self) -> anyhow::Result<()> {
        let app = self.create_router();
        let addr = format!("{}:{}", self.config.host, self.config.port);

        tracing::info!("HTTP服务器启动在 {}", addr);

        let listener = tokio::net::TcpListener::bind(&addr).await?;
        axum::serve(listener, app).await?;

        Ok(())
    }
}

/// 根路径处理器
async fn root_handler() -> Json<serde_json::Value> {
    Json(json!({
        "name": "Data Gateway API",
        "version": env!("CARGO_PKG_VERSION"),
        "status": "running",
        "endpoints": {
            "health": "/health",
            "status": "/status",
            "query": "/query"
        }
    }))
}
